import { call, put, all, takeEvery } from "redux-saga/effects";
import Router from "next/router";

import { Creators as AuthCreators } from "redux/actions/auth";
import { Creators as LoginCreators } from "redux/actions/login";
import { LoginTypes } from "redux/constants";
import { api } from "redux/api";
import interceptResponse from "redux/api/interceptResponse";
import interceptError from "redux/api/interceptError";
import { setCookie } from "redux/api/cookie";

function* getLogin({ payload }) {
  try {
    const { email, password } = payload;
    // yield call(api.setHeader,"Authorization","ZWFkY3Vyc291c2VyOmVhZGN1cnNvcGFzc3dvcmQ=");
    const response = yield call(api.post, "/api/login", {
      email,
      password,
    });
    yield interceptResponse(response);
    if (response.data?.code !== 1000) {
      throw response;
    }
    yield call(setCookie, "access_token", response.data.data.token);
    yield put(AuthCreators.getSuccess(response.data));
    yield put(LoginCreators.getSuccess());
    yield call(Router.reload());
    // yield call(Router.replace, { pathname: "/" });
  } catch (err) {
    yield interceptError(LoginCreators.getFailure, err);
  }
}

export default function* () {
  yield all([takeEvery(LoginTypes.GET_REQUEST, getLogin)]);
}
